package embyparse.noobparser;

import embyparse.parsetree.LiteralNode;
import embyparse.parsetree.ParseNode;
import embyparse.tokenizer.Token;

public class TokenAnalyzer {
/*
	public static void main(String[] args){

		Token t = new Token("p");
		ParseNode p = analyzeToken(t);
		System.out.println(p.getClass());
		System.out.println(p.tag);
	}
	*/
	public static ParseNode analyzeToken(Token t){

		//System.out.println("token: "+t+", line: "+t.line());

		String token = t.getString();
		if(token.equals("true")){
			return LiteralNode.generateBool(true, t.line());
		}
		if(token.equals("false")){
			return LiteralNode.generateBool(false, t.line());
		}
		if(token.equals("null")){
			return LiteralNode.generateNull( t.line());
		}

		for(int i = 0; i<PatternDefinitions.rawpatterns.size();i++){
			ParseNode node = PatternDefinitions.rawpatterns.get(i).match(t);
			if(node!=null){
				//System.out.println("rawpattern line: "+node.lineNumber);
				if(isInfixOperator(token)) return node.setInfixOperator(true);
				return node;
			}
		}
		//System.out.println("oops!");
		//if a keyword

		try{
			int i = Integer.parseInt(token);
			return LiteralNode.generateInt(i,t.line());
		}catch(NumberFormatException e){
		}
		try{
			double d = Double.parseDouble(token);
			return LiteralNode.generateDouble(d,t.line());
		}catch(NumberFormatException e){
		}
		//string literal
		String s = isStringLiteral(token);
		if(s!=null){
			return LiteralNode.generateString(s,t.line());
		}

		//variable
		return new ParseNode(PatternDefinitions.VAR,t,null);
	}

	private static boolean isInfixOperator(String s){
		for(int i = 0; i<Constants.INFIX_OPERATORS.length;i++){
			if(Constants.INFIX_OPERATORS[i].equals(s)){
				return true;
			}
		}
		return false;
	}



	private static String isStringLiteral(String token){
		if( (token.charAt(0) =='"') && (token.charAt(token.length()-1) =='"')){
			return token.substring(1, token.length()-1);
		}
		return null;
	}
}
